package com.kaichaohulian.baocms.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kaichaohulian.baocms.DownloadService;
import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.UserInfoManager;
import com.kaichaohulian.baocms.activity.AdvertMgActivity;
import com.kaichaohulian.baocms.activity.AdvertmassActivity;
import com.kaichaohulian.baocms.activity.ChangeRechargeActivity;
import com.kaichaohulian.baocms.activity.InvitationmgActivity;
import com.kaichaohulian.baocms.activity.LoginActivity;
import com.kaichaohulian.baocms.activity.MeAboutActivity;
import com.kaichaohulian.baocms.activity.MeSettingsActivity;
import com.kaichaohulian.baocms.activity.MyAlbumActivity;
import com.kaichaohulian.baocms.activity.PersonalActivity;
import com.kaichaohulian.baocms.activity.PocketActivity;
import com.kaichaohulian.baocms.activity.RealnameActivity;
import com.kaichaohulian.baocms.activity.RechargeActivity;
import com.kaichaohulian.baocms.activity.SendinvitationActivity;
import com.kaichaohulian.baocms.activity.SmallChangeActivity;
import com.kaichaohulian.baocms.activity.WithdrawApplyActivity;
import com.kaichaohulian.baocms.app.ActivityUtil;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.circledemo.FriendCircleActivity;
import com.kaichaohulian.baocms.ecdemo.common.utils.ToastUtil;
import com.kaichaohulian.baocms.entity.VersionBean;
import com.kaichaohulian.baocms.http.HttpResult;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.retrofit.RetrofitClient;
import com.kaichaohulian.baocms.rxjava.BaseObjObserver;
import com.kaichaohulian.baocms.rxjava.RxUtils;
import com.kaichaohulian.baocms.view.CircleTransform;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.kaichaohulian.baocms.R.id.btn_loginout;
import static com.kaichaohulian.baocms.R.id.me_relativelayout_OnlineService;

/**
 * Created by Administrator on 2015/12/11.
 */
public class MoreFragment extends Fragment {


    @BindView(R.id.me_head_name)
    TextView meHeadName;

    @BindView(R.id.me_buyer_phone)
    TextView meBuyerPhone;
    @BindView(R.id.me_head_right_arrow)
    ImageView meHeadRightArrow;

    @BindView(R.id.me_name)
    RelativeLayout meName;
    @BindView(R.id.layout_personal)
    RelativeLayout layoutPersonal;
    @BindView(R.id.layout_shiming)
    RelativeLayout layoutShiming;
    @BindView(R.id.layout_shenqing)
    RelativeLayout layoutShenqing;
    @BindView(R.id.layout_fabu)
    RelativeLayout layoutFabu;
    @BindView(R.id.me_album_icon)
    ImageView meAlbumIcon;
    @BindView(R.id.me_album_text)
    TextView meAlbumText;
    @BindView(R.id.me_relativelayout_album)
    RelativeLayout meRelativelayoutAlbum;
    @BindView(R.id.layout_lingqian)
    RelativeLayout layoutLingqian;
    @BindView(R.id.layout_chognzhi)
    RelativeLayout layoutChognzhi;
    @BindView(R.id.layout_tixian)
    RelativeLayout layoutTixian;
    @BindView(R.id.me_relativelayout_MassAdvertising)
    RelativeLayout meRelativelayoutMassAdvertising;
    @BindView(R.id.me_relativelayout_Advertising_manager)
    RelativeLayout meRelativelayoutAdvertisingManager;
    @BindView(me_relativelayout_OnlineService)
    RelativeLayout meRelativelayoutOnlineService;
    @BindView(R.id.me_settings_icon)
    ImageView meSettingsIcon;
    @BindView(R.id.me_settings_text)
    TextView meSettingsText;
    @BindView(R.id.me_relativelayout_settings)
    RelativeLayout meRelativelayoutSettings;
    @BindView(R.id.me_about_icon)
    ImageView meAboutIcon;
    @BindView(R.id.me_about_text)
    TextView meAboutText;
    @BindView(R.id.me_relativelayout_about)
    RelativeLayout meRelativelayoutAbout;
    @BindView(R.id.tv_version_num)
    TextView tvVersionNum;
    @BindView(R.id.me_relativelayout_version)
    RelativeLayout meRelativelayoutVersion;
    @BindView(R.id.me_relativelayout_SendInvitation)
    RelativeLayout meRelativelayoutSendInvitation;
    @BindView(R.id.me_relativelayout_invitationManager)
    RelativeLayout meRelativelayoutInvitationManager;
    @BindView(R.id.me_pocket_icon)
    ImageView mePocketIcon;
    @BindView(R.id.me_pocket_text)
    TextView mePocketText;
    @BindView(R.id.me_relativelayout_pocket)
    RelativeLayout meRelativelayoutPocket;
    @BindView(R.id.btn_loginout)
    Button btnLoginout;
    Unbinder unbinder;
    @BindView(R.id.me_head_icon)
    ImageView meHeadIcon;
    @BindView(R.id.text_register)
    TextView textRegister;
    @BindView(R.id.layout_nologin)
    LinearLayout layoutNologin;
    @BindView(R.id.me_buyer_number)
    TextView meBuyerNumber;
    @BindView(R.id.im_QrCode)
    ImageView imQrCode;
    @BindView(R.id.layout_name_id_count)
    LinearLayout layoutNameIdCount;
    private String userID;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_mine, null);

        unbinder = ButterKnife.bind(this, view);

        try {
            userID = MyApplication.getInstance().UserInfo.getUserId() + "";
            if (TextUtils.isEmpty(MyApplication.getInstance().UserInfo.getUserId() + "")) {
                layoutNologin.setVisibility(View.VISIBLE);
                layoutNameIdCount.setVisibility(View.GONE);
                btnLoginout.setVisibility(View.GONE);
            } else if (MyApplication.getInstance().UserInfo.getUserId() == 0) {
                layoutNologin.setVisibility(View.VISIBLE);
                layoutNameIdCount.setVisibility(View.GONE);
                btnLoginout.setVisibility(View.GONE);
            } else {
                layoutNologin.setVisibility(View.GONE);
                layoutNameIdCount.setVisibility(View.VISIBLE);
                btnLoginout.setVisibility(View.VISIBLE);
                Glide.with(MyApplication.getInstance()).load(MyApplication.getInstance().UserInfo.getAvatar())
                        .error(R.mipmap.default_useravatar)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .transform(new CircleTransform(getActivity()))
                        .into(meHeadIcon);
                meHeadName.setText(MyApplication.getInstance().UserInfo.getUsername());
                meBuyerNumber.setText("账号:" + MyApplication.getInstance().UserInfo.getPhoneNumber() + "");
                String userid = String.valueOf(MyApplication.getInstance().UserInfo.getUserId());

                if (!TextUtils.isEmpty(userid) && !"null".equals(userid)) {
                    meBuyerNumber.setText("ID:" + userid);
                } else {
                    meBuyerNumber.setText("暂未获取到账号");
                }

                Glide.with(MyApplication.getInstance()).load(Url.BASE_URL + MyApplication.getInstance().UserInfo.getQrCode()).diskCacheStrategy(DiskCacheStrategy.ALL).into(imQrCode);


            }
        } catch (Exception e) {

        }


        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.me_head_name, R.id.me_buyer_phone, R.id.me_head_right_arrow, R.id.me_name, R.id.layout_personal, R.id.layout_shiming, R.id.layout_shenqing, R.id.layout_fabu, R.id.me_album_icon, R.id.me_album_text, R.id.me_relativelayout_album, R.id.layout_lingqian, R.id.layout_chognzhi, R.id.layout_tixian, R.id.me_relativelayout_MassAdvertising, R.id.me_relativelayout_Advertising_manager, me_relativelayout_OnlineService, R.id.me_settings_icon, R.id.me_settings_text, R.id.me_relativelayout_settings, R.id.me_about_icon, R.id.me_about_text, R.id.me_relativelayout_about, R.id.tv_version_num, R.id.me_relativelayout_version, R.id.me_relativelayout_SendInvitation, R.id.me_relativelayout_invitationManager, R.id.me_pocket_icon, R.id.me_pocket_text, R.id.me_relativelayout_pocket, btn_loginout, R.id.me_head_icon, R.id.text_register, R.id.layout_nologin, R.id.me_buyer_number, R.id.im_QrCode, R.id.layout_name_id_count})
    public void onViewClicked(View view) {

        if (TextUtils.isEmpty(userID)) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        } else if (userID.equals("0")) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        } else if (view.getId() == R.id.me_relativelayout_OnlineService) {
            ActivityUtil.next(getActivity(), SendinvitationActivity.class);

        } else if (view.getId() == R.id.me_relativelayout_about || view.getId() == R.id.me_about_icon || view.getId() == R.id.me_about_text) {
//跳转到关于我们
            ActivityUtil.next(getActivity(), MeAboutActivity.class);
        } else if (view.getId() == R.id.me_relativelayout_version) {
            //跳转到版本更新
            checkVersion();
        } else {

            switch (view.getId()) {


                //个人信息
                case R.id.me_head_icon:
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), PersonalActivity.class);
                    startActivityForResult(intent, 1000);


//                        ActivityUtil.next(getActivity(), PersonalActivity.class);
                    break;
                case R.id.layout_name_id_count:
//                        ActivityUtil.next(getActivity(), PersonalActivity.class);
                    Intent intent2 = new Intent();
                    intent2.setClass(getActivity(), PersonalActivity.class);
                    startActivityForResult(intent2, 1000);
                    break;

                case R.id.me_head_name:
//                        ActivityUtil.next(getActivity(), PersonalActivity.class);
                    Intent intent3 = new Intent();
                    intent3.setClass(getActivity(), PersonalActivity.class);
                    startActivityForResult(intent3, 1000);
                    break;

                case R.id.me_buyer_phone:
//                        ActivityUtil.next(getActivity(), PersonalActivity.class);
                    Intent intent4 = new Intent();
                    intent4.setClass(getActivity(), PersonalActivity.class);
                    startActivityForResult(intent4, 1000);
                    break;
                case R.id.me_head_right_arrow:
//                        ActivityUtil.next(getActivity(), PersonalActivity.class);
                    Intent intent5 = new Intent();
                    intent5.setClass(getActivity(), PersonalActivity.class);
                    startActivityForResult(intent5, 1000);
                    break;
                case R.id.im_QrCode:
                    break;
                case R.id.me_name:
                    break;
                case R.id.layout_personal:
                    ActivityUtil.next(getActivity(), PersonalActivity.class);
                    break;
                //实名认证
                case R.id.layout_shiming:
                    startActivity(new Intent(getActivity(), RealnameActivity.class));
                    break;
                case R.id.layout_shenqing:
                    startActivity(new Intent(getActivity(), SmallChangeActivity.class));
                    break;
                //我的发布
                case R.id.layout_fabu:
                    ActivityUtil.next(getActivity(), FriendCircleActivity.class);
                    break;
                //我的相册
                case R.id.me_album_icon:
                    ActivityUtil.next(getActivity(), MyAlbumActivity.class);
                    break;
                case R.id.me_album_text:
                    ActivityUtil.next(getActivity(), MyAlbumActivity.class);
                    break;
                //相册
                case R.id.me_relativelayout_album:
                    ActivityUtil.next(getActivity(), MyAlbumActivity.class);
                    break;
//                     <!--零钱-->
                case R.id.layout_lingqian:
                    ActivityUtil.next(getActivity(), RechargeActivity.class);
                    break;
                //充值
                case R.id.layout_chognzhi:
                    ActivityUtil.next(getActivity(), ChangeRechargeActivity.class);
                    break;
                //体现
                case R.id.layout_tixian:
                    ActivityUtil.next(getActivity(), WithdrawApplyActivity.class);
                    break;
                //群发广告
                case R.id.me_relativelayout_MassAdvertising:
                    ActivityUtil.next(getActivity(), AdvertmassActivity.class);
                    break;
                //广告管理
                case R.id.me_relativelayout_Advertising_manager:
                    ActivityUtil.next(getActivity(), AdvertMgActivity.class);
                    break;
                //客服咨询
                   /* case me_relativelayout_OnlineService:
//                        ActivityUtil.next(getActivity(), SendinvitationActivity.class);
                        break;*/
                //设置
                case R.id.me_settings_icon:
                    ActivityUtil.next(getActivity(), MeSettingsActivity.class);
                    break;
                case R.id.me_settings_text:
                    ActivityUtil.next(getActivity(), MeSettingsActivity.class);
                    break;
                case R.id.me_relativelayout_settings:
                    ActivityUtil.next(getActivity(), MeSettingsActivity.class);
                    break;
                //关于
                case R.id.me_about_icon:
                    ActivityUtil.next(getActivity(), MeAboutActivity.class);
                    break;
                case R.id.me_about_text:
                    ActivityUtil.next(getActivity(), MeAboutActivity.class);
                    break;
                case R.id.me_relativelayout_about:
                    ActivityUtil.next(getActivity(), MeAboutActivity.class);
                    break;
                case R.id.tv_version_num:
                    checkVersion();
                    break;
                case R.id.me_relativelayout_version:
                    checkVersion();
                    break;
                //发出邀请
                case R.id.me_relativelayout_SendInvitation:
                    ActivityUtil.next(getActivity(), SendinvitationActivity.class);
                    break;
                //邀请管理
                case R.id.me_relativelayout_invitationManager:
                    Intent intent6 = new Intent(getActivity(), InvitationmgActivity.class);
                    intent6.putExtra("type", "ProFile");
                    startActivity(intent6);
                    break;
                //钱包
                case R.id.me_pocket_icon:
                    UserInfoManager.getInstance().updateUserCache(getActivity());
                    ActivityUtil.next(getActivity(), PocketActivity.class);
                    break;
                case R.id.me_pocket_text:
                    UserInfoManager.getInstance().updateUserCache(getActivity());
                    ActivityUtil.next(getActivity(), PocketActivity.class);
                    break;
                case R.id.me_relativelayout_pocket:
                    UserInfoManager.getInstance().updateUserCache(getActivity());
                    ActivityUtil.next(getActivity(), PocketActivity.class);
                    break;
                case R.id.btn_loginout:
                    break;

                case R.id.text_register:
                    break;
                case R.id.layout_nologin:
                    break;
                case R.id.me_buyer_number:
                    break;


            }


        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Glide.with(MyApplication.getInstance()).load(MyApplication.getInstance().UserInfo.getAvatar())
                .error(R.mipmap.default_useravatar)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .transform(new CircleTransform(getActivity()))
                .into(meHeadIcon);
//        me_head_name
        meHeadName.setText(MyApplication.getInstance().UserInfo.getUsername());
    }

    private void checkVersion() {
        RetrofitClient.getInstance().createApi().checkVersion()
                .compose(RxUtils.<HttpResult<VersionBean>>io_main())
                .subscribe(new BaseObjObserver<VersionBean>(getActivity()) {
                    @Override
                    protected void onHandleSuccess(VersionBean versionBean) {
                        if (!versionBean.getAndroidVersion().equals(getVersion())) {
                            openRedPackageDialog("http://47.94.229.40/ZFishApp/" + versionBean.getAndroidPath());
                            tvVersionNum.setVisibility(View.VISIBLE);
                        } else {
                            tvVersionNum.setVisibility(View.GONE);
                            Toast.makeText(getActivity(), "当前已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = getActivity().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            Log.e("gy", "版本号：" + version);
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 版本对话框
     */
    private void openRedPackageDialog(final String path) {
        View view = View.inflate(getActivity(), R.layout.dialog_version, null);
        ImageView dialogClose = (ImageView) view.findViewById(R.id.img_verson_close);
        ImageView dialogCancle = (ImageView) view.findViewById(R.id.tv_verson_cancle);
        TextView dialogSure = (TextView) view.findViewById(R.id.tv_verson_sure);
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog_type);
        dialog.setContentView(view);
        dialog.show();

        dialogClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialogCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialogSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showMessage("后台更新中");
                Intent intent = new Intent(getActivity(), DownloadService.class);
                intent.putExtra("path", path);
//                intent.putExtra("path", "http://d.koudai.com/com.koudai.weishop/1000f/weishop_1000f.apk");
                getActivity().startService(intent);
                tvVersionNum.setVisibility(View.GONE);
                dialog.dismiss();
            }
        });
    }


}
